package cn.tiger.service;

import cn.tiger.common.CodeMsg;
import cn.tiger.exception.ConversationException;
import cn.tiger.pojo.domain.Conversation;
import cn.tiger.pojo.domain.Message;
import cn.tiger.pojo.dto.AskQuestionRequest;
import cn.tiger.pojo.dto.CreateConversationRequest;
import cn.tiger.pojo.vo.AskQuestionResponse;
import cn.tiger.pojo.vo.ConversationVO;
import cn.tiger.pojo.vo.MessageVO;
import cn.tiger.repository.ConversationRepository;
import cn.tiger.repository.MessageRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 对话服务类
 * 
 * 提供AI问答对话相关的业务逻辑处理，包括对话创建、问答交互、历史管理等功能
 * 集成阿里云通义千问Qwen-Plus模型，实现智能对话交互功能
 * 支持事务管理、异常处理和数据转换功能
 * 
 * @author AI Backend Team
 * @version 1.0
 * @since 2025-09-26
 */
@Slf4j // 启用Lombok日志功能
@Service // Spring服务层注解
@RequiredArgsConstructor // Lombok注解，生成构造函数
public class ConversationService {
    
    /** 对话数据仓库接口，用于对话信息的CRUD操作 */
    private final ConversationRepository conversationRepository;
    /** 消息数据仓库接口，用于消息信息的CRUD操作 */
    private final MessageRepository messageRepository;
    /** AI服务接口，用于调用阿里云通义千问模型 */
    private final AiService aiService;
    /** 会员服务接口，用于会员权限验证 */
    private final MembershipService membershipService;
    
    /**
     * 创建新对话
     * 
     * 根据眨户请求创建一个新的AI对话会话，初始化对话的基本信息
     * 包括对话标题、上下文描述、创建时间等，使用事务管理确保数据一致性
     * 
     * @param request 创建对话请求对象，包含用户ID、标题和描述
     * @return 新创建的对话ID
     */
    @Transactional // 事务管理注解，确保数据一致性
    public Long createConversation(CreateConversationRequest request) {
        // 检查用户是否可以创建新对话
        long currentConversationCount = conversationRepository.countByUserIdAndStatus(request.getUserId(), (byte) 1);
        if (!membershipService.canCreateConversation(request.getUserId(), currentConversationCount)) {
            throw new ConversationException(
                new CodeMsg(400, String.format("免费用户最多只能创建%d个对话，请升级VIP会员享受无限制对话", 
                    MembershipService.FREE_MAX_CONVERSATIONS))
            );
        }
        
        Conversation conversation = new Conversation();
        conversation.setUserId(request.getUserId());
        conversation.setTitle(request.getTitle());
        conversation.setContext(request.getDescription());
        conversation.setCreateTime(LocalDateTime.now());
        conversation.setUpdateTime(LocalDateTime.now());
        conversation.setStatus((byte) 1);
        
        Conversation saved = conversationRepository.save(conversation);
        log.info("创建新对话成功，对话ID: {}", saved.getId());
        return saved.getId();
    }
    
    /**
     * 提问并获取AI回答
     * 
     * 处理用户提问请求，调用阿里云通义千问模型获取AI回答
     * 支持创建新对话或在现有对话中继续问答，包含对话权限检查
     * 使用事务管理确保用户消息和AI回复都被正确保存
     * 
     * @param request 提问请求对象，包含问题内容、用户ID和对话ID(可选)
     * @return 提问响应对象，包含用户消息和AI回复
     * @throws ConversationException 当对话不存在或没有权限时抛出
     */
    @Transactional
    public AskQuestionResponse askQuestion(AskQuestionRequest request) {
        Long conversationId = request.getConversationId();
        boolean isNewConversation = false;
        
        // 如果没有对话ID，创建新对话
        if (conversationId == null) {
            CreateConversationRequest createRequest = new CreateConversationRequest();
            createRequest.setUserId(request.getUserId());
            createRequest.setTitle(request.getTitle() != null ? request.getTitle() : 
                    request.getQuestion().length() > 20 ? 
                    request.getQuestion().substring(0, 20) + "..." : 
                    request.getQuestion());
            conversationId = createConversation(createRequest);
            isNewConversation = true;
        } else {
            // 验证对话是否存在且属于该用户
            Conversation existingConversation = conversationRepository.findByUserIdAndId(request.getUserId(), conversationId);
            if (existingConversation == null) {
                throw new ConversationException(new CodeMsg(404, "对话不存在或不属于当前用户"));
            }
            
            // 检查用户是否可以在此对话中发送消息
            long userMessageCount = messageRepository.countByConversationIdAndSenderType(conversationId, "user");
            if (!membershipService.canSendMessage(request.getUserId(), userMessageCount)) {
                throw new ConversationException(
                    new CodeMsg(403, "请升级VIP会员，享受无限对话")
                );
            }
        }
        
        // 确保对话存在
        if (conversationId == null) {
            throw new ConversationException(new CodeMsg(400, "对话ID不能为空"));
        }
        
        // 再次验证对话是否存在
        Conversation conversation = conversationRepository.findById(conversationId).orElse(null);
        if (conversation == null) {
            throw new ConversationException(new CodeMsg(404, "对话不存在，ID: " + conversationId));
        }
        
        // 在保存消息之前检查用户是否可以发送消息
        long currentUserMessageCount = messageRepository.countByConversationIdAndSenderType(conversationId, "user");
        log.info("检查会员限制 - 用户ID: {}, 当前消息数: {}, 最大限制: {}", 
                request.getUserId(), currentUserMessageCount, MembershipService.FREE_MAX_MESSAGES_PER_CONVERSATION);
        
        boolean canSend = membershipService.canSendMessage(request.getUserId(), currentUserMessageCount);
        log.info("用户是否可以发送消息: {}", canSend);
        
        if (!canSend) {
            log.warn("用户{}已达到消息限制，当前消息数: {}", request.getUserId(), currentUserMessageCount);
            throw new ConversationException(
                new CodeMsg(403, "请升级VIP会员，享受无限对话")
            );
        }
        
        // 保存用户消息
        Message userMessage = new Message();
        userMessage.setConversationId(conversationId);
        userMessage.setSenderType("user");
        userMessage.setContent(request.getQuestion());
        userMessage.setSendTime(LocalDateTime.now());
        userMessage.setMessageType("TEXT");
        userMessage.setStatus((byte) 1);
        Message savedUserMessage = messageRepository.save(userMessage);
        
        // 获取AI回答
        String aiResponse = aiService.getAiResponse(
                aiService.buildMessages(conversationId, request.getQuestion())
        );
        
        // 保存AI回答
        Message aiMessage = new Message();
        aiMessage.setConversationId(conversationId);
        aiMessage.setSenderType("system");
        aiMessage.setContent(aiResponse);
        aiMessage.setSendTime(LocalDateTime.now());
        aiMessage.setMessageType("TEXT");
        aiMessage.setStatus((byte) 1);
        Message savedAiMessage = messageRepository.save(aiMessage);
        
        // 更新对话时间
        conversation.setUpdateTime(LocalDateTime.now());
        conversationRepository.save(conversation);
        
        // 构建响应
        AskQuestionResponse response = new AskQuestionResponse();
        response.setConversationId(conversationId);
        response.setUserMessage(convertToMessageVO(savedUserMessage));
        response.setAiResponse(convertToMessageVO(savedAiMessage));
        response.setResponseTime(LocalDateTime.now());
        response.setIsNewConversation(isNewConversation);
        
        return response;
    }
    
    /**
     * 获取用户的对话列表
     * @param userId 用户ID
     * @return 对话列表
     */
    public List<ConversationVO> getUserConversations(Long userId) {
        List<Conversation> conversations = conversationRepository
                .findByUserIdAndStatusOrderByUpdateTimeDesc(userId, (byte) 1);
        
        return conversations.stream().map(this::convertToConversationVO).collect(Collectors.toList());
    }
    
    /**
     * 获取对话详情
     * @param conversationId 对话ID
     * @param userId 用户ID
     * @return 对话详情
     */
    public ConversationVO getConversationDetail(Long conversationId, Long userId) {
        Conversation conversation = conversationRepository.findByUserIdAndId(userId, conversationId);
        if (conversation == null) {
            return null;
        }
        return convertToConversationVO(conversation);
    }
    
    /**
     * 获取对话中的消息列表
     * @param conversationId 对话ID
     * @return 消息列表
     */
    public List<MessageVO> getConversationMessages(Long conversationId) {
        List<Message> messages = messageRepository.findByConversationIdOrderBySendTimeAsc(conversationId);
        return messages.stream().map(this::convertToMessageVO).collect(Collectors.toList());
    }
    
    /**
     * 删除对话
     * @param conversationId 对话ID
     * @param userId 用户ID
     * @return 是否成功
     */
    @Transactional
    public boolean deleteConversation(Long conversationId, Long userId) {
        Conversation conversation = conversationRepository.findByUserIdAndId(userId, conversationId);
        if (conversation != null) {
            conversation.setStatus((byte) 0);
            conversationRepository.save(conversation);
            return true;
        }
        return false;
    }
    
    /**
     * 转换为ConversationVO
     */
    private ConversationVO convertToConversationVO(Conversation conversation) {
        ConversationVO vo = new ConversationVO();
        vo.setId(conversation.getId());
        vo.setTitle(conversation.getTitle());
        vo.setCreateTime(conversation.getCreateTime());
        vo.setUpdateTime(conversation.getUpdateTime());
        vo.setStatus(conversation.getStatus());
        
        // 获取消息数量
        long messageCount = messageRepository.countByConversationId(conversation.getId());
        vo.setMessageCount(messageCount);
        
        // 获取最后一条消息
        Message lastMessage = messageRepository.findLastMessageByConversationId(conversation.getId());
        if (lastMessage != null) {
            vo.setLastMessage(lastMessage.getContent());
        }
        
        return vo;
    }
    
    /**
     * 转换为MessageVO
     */
    private MessageVO convertToMessageVO(Message message) {
        MessageVO vo = new MessageVO();
        vo.setId(message.getId());
        vo.setSenderType(message.getSenderType());
        vo.setContent(message.getContent());
        vo.setSendTime(message.getSendTime());
        vo.setMessageType(message.getMessageType());
        vo.setStatus(message.getStatus());
        return vo;
    }
    
    /**
     * 获取对话中用户发送的消息数量
     * @param conversationId 对话ID
     * @return 用户消息数量
     */
    public long getUserMessageCount(Long conversationId) {
        return messageRepository.countByConversationIdAndSenderType(conversationId, "user");
    }
    
    /**
     * 获取用户在当前对话中的剩余提问次数
     * @param userId 用户ID
     * @param currentMessageCount 当前消息数量
     * @return 剩余提问次数，-1表示无限制
     */
    public int getRemainingQuestions(Long userId, long currentMessageCount) {
        if (membershipService.isVipMember(userId)) {
            return -1; // VIP用户无限制
        }
        
        // 免费用户限制
        int maxMessages = MembershipService.FREE_MAX_MESSAGES_PER_CONVERSATION;
        return Math.max(0, maxMessages - (int) currentMessageCount);
    }
}
